<script setup>
import { Modal } from 'ant-design-vue'
import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons-vue'
import menuModal from './components/menu-modal.vue'
import { addMenu, deleteMenu, getMenu, updateMenu } from '~@/api/system/index'
// 引入 Pinia store
defineOptions({
  name: 'Menusys',
})
const userStore = useUserStore()
const { hasPermission } = userStore
const message = useMessage()
const menuData = shallowRef([])
const expandedKeys = shallowRef([])
// 当前选择的菜单
const selectedKeys = shallowRef([])
// 弹窗显示状态
const loading = ref(false)
const form = reactive({
  title: '',
  component: '',
  path: '',
  name: '',
  icon: '',
  resOrder: null,
  parentId: null,
  resType: 'C',
  permission: '',
})
const menuInfo = reactive({
  title: '',
  component: '',
  path: '',
  name: '',
  icon: '',
  resOrder: null,
  parentId: null,
  resType: 'C',
  keepAlive: null,
})
const formData = reactive({ name: '', path: '', parentId: null })
// 新增编辑弹窗
const modalVisible = ref(false)
const modalType = ref('add')
const currentId = ref(0)
const menuForm = ref()
const menuOpen = ref(false)
const menuTitle = ref('')
const titleMap = {
  add: '新增菜单',
  edit: '编辑菜单',
  children: '新增子菜单',
}
// 表格列
const columns = shallowRef([
  {
    title: '菜单名称',
    dataIndex: 'title',
  },
  {
    title: '菜单排序',
    dataIndex: 'resOrder',
    align: 'center',
  },
  {
    title: '权限标识',
    dataIndex: 'permission',
    align: 'center',
  },
  {
    title: '菜单路径',
    dataIndex: 'path',
  },

  {
    title: '菜单图标',
    dataIndex: 'icon',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
  },
])
const rowSelection = ref({
  checkStrictly: false,
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
  },
  onSelect: (record, selected, selectedRows) => {
    console.log(record, selected, selectedRows)
  },
  onSelectAll: (selected, selectedRows, changeRows) => {
    console.log(selected, selectedRows, changeRows)
  },
})
onMounted(() => {
  init()
})
//
async function init() {
  if (loading.value)
    return
  loading.value = true
  try {
    const { data } = await getMenu({})
    menuData.value = data ?? []
    loading.value = false
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}
// 打开弹窗
function openModal(type, record) {
  if (type === 'add') {
    menuTitle.value = '新增菜单'
    resetForm()
  }
  else if (type === 'edit') {
    menuTitle.value = '编辑菜单'
    form.title = record.title
    form.component = record.component
    form.title = record.title
    form.name = record.name
    form.path = record.path
    form.icon = record.icon
    form.resOrder = record.resOrder
    form.parentId = record.parentId
    form.resType = record.resType
    form.permission = record.permission
    form.keepAlive = record.keepAlive
    form.id = record.id
    // currentId.value = record.id || 0
  }
  else if (type === 'children') {
    resetForm()
    menuTitle.value = '新增子菜单'
    form.resType = 'C'
    // console.log(record)
    // if (record && record.children) {
    //   form.parentId = record.parentId
    // }
    // else {
    form.parentId = record.id
    // }

    form.id = record.id
    // currentId.value = record.id || 0
  }
  modalType.value = type
  menuOpen.value = true
}
// 重置表单
function resetForm() {
  form.title = ''
  form.component = ''
  form.name = ''
  form.path = ''
  form.icon = ''
  form.resOrder = null
  form.parentId = null
  form.resType = 'C'
  form.id = null
  form.permission = ''
  form.keepAlive = null
}
// 确认操作
async function handleOk() {
  try {
    await menuForm.value.validateFields()
    if (menuTitle.value === '编辑菜单') {
      const { data } = await updateMenu(form)
      menuOpen.value = false
      init()
      message.success('保存成功')
    }
    else {
      const { data } = await addMenu(form)
      menuOpen.value = false
      init()
      message.success('添加成功')
    }
  }
  catch (err) {
    console.log(err)
  }
}

// 处理类型
function handleType(e) {
  form.resType = e.target.value
  // console.log(e.target.value)
}

// 删除菜单
async function handleDelete(record) {
  Modal.confirm({
    title: '确认操作',
    content: `确定要删除 “ ${record.title} ” 吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      return new Promise((resolve, reject) => {
        const res = deleteMenu({ id: record.id, type: record.resType })
          .then((res) => {
            if (res.data.code === 'SUCCESS') {
              message.success('操作成功')
              init()
              resolve() // 关闭对话框
            }
            else {
              message.error('操作失败')
              reject() // 保持对话框打开
            }
          })
          .catch(() => {
            // message.error('操作失败')
            reject() // 保持对话框打开
          })
      })
    },
    onCancel() {
      console.log('取消操作')
    },
  })
}

// 展开子节点
function handleExpand(expandedKeys) {
  selectedKeys.value = expandedKeys
}
</script>

<template>
  <page-container>
    <a-card title="菜单管理" bordered>
      <template v-if="hasPermission('system:menu:add')" #extra>
        <a-space size="middle">
          <a-button type="primary" @click="openModal('add')">
            <template #icon>
              <PlusOutlined />
            </template>
            新增菜单
          </a-button>
        </a-space>
      </template>

      <!-- 菜单管理表格 -->
      <a-table :columns="columns" :data-source="menuData" :row-key="record => record.id" :loading="loading">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'action'">
            <a-space :size="8">
              <a-button type="link" @click="openModal('edit', record)">
                <EditOutlined />修改
              </a-button>
              <a-button type="link" @click="openModal('children', record)">
                <PlusOutlined />新增
              </a-button>
              <a-button type="link" @click="handleDelete(record)">
                <DeleteOutlined />删除
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
      <!-- <menu-modal :id="currentId" :visible="modalVisible" :type="modalType" /> -->
      <!-- 编辑菜单弹窗 -->
      <!-- 添加菜单 -->
      <a-modal v-model:open="menuOpen" :mask-closable="false" :title="menuTitle" width="800px" :body-style="{ paddingTop: '30px', paddingBottom: '30px' }" @ok="handleOk">
        <a-form ref="menuForm" :model="form">
          <a-row :gutter="24">
            <a-col v-if="menuTitle !== '新增菜单'" :span="24">
              <a-form-item label="父级菜单" name="parentId" :label-col="{ span: 4 }">
                <a-tree-select
                  v-model:value="form.parentId"
                  style="width:565px" :tree-data="menuData" tree-default-expand-all
                  placeholder="请选择父级菜单" :field-names="{ children: 'children', title: 'title', key: 'id', value: 'id' }"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-item
                label="菜单名称" name="title" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }"
                :rules="[{ required: true, message: '请输入菜单名称' }]"
              >
                <a-input v-model:value="form.title" placeholder="请输入菜单名称" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="菜单类型" name="resType" :label-col="{ span: 4 }">
                <a-radio-group v-model:value="form.resType" name="radioGroup" @change="handleType">
                  <a-radio value="C">
                    目录
                  </a-radio>
                  <a-radio value="M">
                    菜单
                  </a-radio>
                  <a-radio value="B">
                    按钮
                  </a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item name="resOrder" label="显示排序" :rules="[{ required: true, message: '请输入显示排序' }]" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }">
                <a-input-number v-model:value="form.resOrder" :min="0" placeholder="菜单排序" style="width: 563px;" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row v-if="form.resType !== 'B'" :gutter="24">
            <a-col :span="24">
              <a-form-item
                label="路由路径" name="path" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }"
                :rules="[{ required: true, message: '请输入路由路径' }]"
              >
                <a-input v-model:value="form.path" placeholder="请输入路由路径" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item
                label="组件路径" name="component" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }"
                :rules="[{ required: true, message: '请输入组件路径' }]"
              >
                <a-input v-model:value="form.component" placeholder="请输入组件路径" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="菜单图标" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }">
                <a-input v-model:value="form.icon" placeholder="菜单图标" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item
                label="缓存名称" name="name" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }"
              >
                <a-input v-model:value="form.name" placeholder="请输入缓存名称" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="是否缓存" :label-col="{ span: 4 }">
                <a-radio-group v-model:value="form.keepAlive" name="radioGroup">
                  <a-radio :value="true">
                    是
                  </a-radio>
                  <a-radio :value="false">
                    否
                  </a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row v-else :gutter="24">
            <a-col :span="24">
              <a-form-item
                label="权限字符" name="permission" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }"
                :rules="[{ required: true, message: '请输入权限字符' }]"
              >
                <a-input v-model:value="form.permission" placeholder="请输入权限字符" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-modal>
    </a-card>
  </page-container>
</template>

  <style lang="less" scoped>
    :deep(.ant-btn){
       padding: 4px 8px;
    }
    .line{
      color:#1677ff;
    }
    .userTitle{
      color:gray;
      width: 100%;
      padding:5px 0;
      border-bottom:1px solid #f1eded;
      margin-bottom: 20px;
    }
    .red{
      color:red;
      /* color:#ff4d4f; */
    }
    .card-title{
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      flex: auto;
      color: rgba(0, 0, 0, 0.88);
      font-weight: 600;
      font-size: 16px;
      line-height: 1.5;
    }
  @media screen and (max-width: 1200px) and (min-width: 992px) {
    .activeCard {
      margin-bottom: 24px;
    }
    .members {
      margin-bottom: 0;
    }
    .extraContent {
      margin-left: -44px;
      .statItem {
        padding: 0 16px;
      }
    }
  }

  @media screen and (max-width: 992px) {
    .activeCard {
      margin-bottom: 24px;
    }
    .members {
      margin-bottom: 0;
    }
    .extraContent {
      float: none;
      margin-right: 0;
      .statItem {
        padding: 0 16px;
        text-align: left;
        &::after {
          display: none;
        }
      }
    }
  }

  @media screen and (max-width: 768px) {
    .extraContent {
      margin-left: -16px;
    }
    .projectList {
      .projectGrid {
        width: 50%;
      }
    }
  }

  @media screen and (max-width: 576px) {
    .pageHeaderContent {
      display: block;
      .content {
        margin-left: 0;
      }
    }
    .extraContent {
      .statItem {
        float: none;
      }
    }
  }

  @media screen and (max-width: 480px) {
    .projectList {
      .projectGrid {
        width: 100%;
      }
    }
  }
  </style>
